package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.Organization;
import com.xmy.cultivate.entity.Quarter;
import com.xmy.cultivate.entity.Staff;
import com.xmy.cultivate.mapper.OrganizationMapper;
import com.xmy.cultivate.service.IOrganizationService;
import com.xmy.cultivate.service.IQuarterService;
import com.xmy.cultivate.service.IStaffService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 组织机构 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-19
 */
@RestController
@RequestMapping("/api/organization")
@Scope("prototype")
public class OrganizationController extends BaseController {

    @Autowired
    @Lazy
    IOrganizationService iOrganizationService;

    @Autowired
    @Lazy
    OrganizationMapper organizationMapper;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    IStaffService iStaffService;

    /**
     * @param pageNum
     * @param pageSize
     * @param type
     * @param schoolId
     * @param yearPart
     * @param quarterNum
     * @param isGetAll   是否获取所有
     * @return
     */
    @GetMapping()
    public Result findAll(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "1000") Integer pageSize,
                          @RequestParam(value = "type", defaultValue = "") String type,
                          @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
                          @RequestParam(value = "name", defaultValue = "", required = false) String name,
                          @RequestParam(value = "yearPart", defaultValue = "", required = false) String yearPart,
                          @RequestParam(value = "quarterNum", defaultValue = "", required = false) String quarterNum,
                          @RequestParam(value = "isGetAll", defaultValue = "0", required = false) Integer isGetAll
    ) {
        try {

            IPage<Organization> iPage = new Page<>(pageNum, pageSize);
            QueryWrapper<Organization> organQueryWrapper = new QueryWrapper<>();
            organQueryWrapper.eq("deleted", 0);
            organQueryWrapper.eq(StringUtils.isNotBlank(type), "type", type);
            organQueryWrapper.like(StringUtils.isNotBlank(name), "name", name);

            if (StringUtils.isNotBlank(schoolId)) {
                organQueryWrapper.eq("id", schoolId);
            } else {
                if (this.isSuper.equals(1)) {
                    if (isGetAll.equals(0)) {
                        if (StringUtils.isBlank(yearPart) && StringUtils.isBlank(quarterNum)) {
                            Quarter quarterNow = iQuarterService.getNowQuarter();
                            yearPart = quarterNow.getYearPart().toString();
                            quarterNum = quarterNow.getNum().toString();
                        }
                        if (StringUtils.isNotBlank(yearPart) && StringUtils.isNotBlank(quarterNum)) {
                            organQueryWrapper.inSql("id", "select school_id from order_apply where deleted = 0 and status <>2 and order_type in(1,3,5) and lesson_type =1 and year_part = " + yearPart + " and quarter_num = " + quarterNum + " group by school_id");
                        }
                    }
                } else {
                    organQueryWrapper.in("id", this.baseSchoolIdList);
                }
            }
            iOrganizationService.page(iPage, organQueryWrapper);
            for (Organization organization : iPage.getRecords()) {
                if (organization.getManageId() != null) {
                    Staff staff = iStaffService.getOneById(organization.getManageId());
                    if (staff != null) {
                        organization.setManageName(staff.getName());
                    }
                }
                if (organization.getType().equals(1)) {
                    organization.setTypeName("校区");
                } else {
                    organization.setTypeName("部门");
                }
            }

            return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
        } catch (Exception e) {
            return new Result(Code.ERROR, "", e.getMessage());
        }
    }


    /**
     * @param pageNum
     * @param pageSize
     * @param type
     * @param schoolId
     * @param startDate
     * @param endDate
     * @return
     */
    @GetMapping("/findForDate")
    public Result findForDate(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "1000") Integer pageSize,
                              @RequestParam(value = "type", defaultValue = "") String type,
                              @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
                              @RequestParam(value = "name", defaultValue = "", required = false) String name,
                              @RequestParam(value = "startDate", defaultValue = "", required = false) String startDate,
                              @RequestParam(value = "endDate", defaultValue = "", required = false) String endDate) {
        try {

            IPage<Organization> iPage = new Page<>(pageNum, pageSize);
            QueryWrapper<Organization> organQueryWrapper = new QueryWrapper<>();
            organQueryWrapper.eq("deleted", 0);
            organQueryWrapper.eq(StringUtils.isNotBlank(type), "type", type);
            organQueryWrapper.like(StringUtils.isNotBlank(name), "name", name);
            if (StringUtils.isNotBlank(endDate) && StringUtils.isNotBlank(startDate)) {
                organQueryWrapper.inSql("id", "select school_id from order_apply where deleted = 0 and status <>2 and lesson_type =1 and handle_date BETWEEN '" + startDate + "' and '" + endDate + "' group by school_id");
            }

            if (StringUtils.isNotBlank(schoolId)) {
                organQueryWrapper.eq("id", schoolId);
            } else {
                if (this.isSuper.equals(1)) {
                } else {
                    organQueryWrapper.in("id", this.baseSchoolIdList);
                }
            }
            organQueryWrapper.orderByDesc("status");
            organQueryWrapper.orderByAsc("id");
            iOrganizationService.page(iPage, organQueryWrapper);
            for (Organization organization : iPage.getRecords()) {
                if (organization.getManageId() != null) {
                    Staff staff = iStaffService.getOneById(organization.getManageId());
                    if (staff != null) {
                        organization.setManageName(staff.getName());
                    }
                }
                if (organization.getType().equals(1)) {
                    organization.setTypeName("校区");
                } else {
                    organization.setTypeName("部门");
                }
            }

            return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
        } catch (Exception e) {
            return new Result(Code.ERROR, "", e.getMessage());
        }
    }


    /**
     * @param pageNum
     * @param pageSize
     * @param type
     * @param schoolId
     * @return
     */
    @GetMapping("/findAllSchool")
    public Result findAllSchool(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "1000") Integer pageSize,
                                @RequestParam(value = "type", defaultValue = "") String type,
                                @RequestParam(value = "name", defaultValue = "", required = false) String name,
                                @RequestParam(value = "status", defaultValue = "") String status,
                                @RequestParam(value = "schoolId", defaultValue = "") String schoolId) {
        try {

            IPage<Organization> iPage = new Page<>(pageNum, pageSize);
            QueryWrapper<Organization> organQueryWrapper = new QueryWrapper<>();
            organQueryWrapper.eq("deleted", 0);
            organQueryWrapper.eq(StringUtils.isNotBlank(type), "type", type);
            organQueryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
            organQueryWrapper.like(StringUtils.isNotBlank(name), "name", name);

            if (StringUtils.isNotBlank(schoolId)) {
                organQueryWrapper.eq("id", schoolId);
            } else {
                if (this.isSuper.equals(1)) {
                } else {
                    organQueryWrapper.in("id", this.baseSchoolIdList);
                }
            }
            iOrganizationService.page(iPage, organQueryWrapper);
            for (Organization organization : iPage.getRecords()) {
                Staff staff = iStaffService.getOneById(organization.getManageId());
                if (staff != null) {
                    organization.setManageName(staff.getName());
                }
                if (organization.getType().equals(1)) {
                    organization.setTypeName("校区");
                } else {
                    organization.setTypeName("部门");
                }
            }

            return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
        } catch (Exception e) {
            return new Result(Code.ERROR, "", e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") String id) {
        try {
            Organization organization = iOrganizationService.getById(id);
            //long ids =  idWorker.nextId();
            //System.out.println(ids);
            return new Result(Code.OK, organization);
        } catch (Exception e) {
            return new Result(Code.ERROR, "", e.getMessage());
        }
    }


    @PostMapping()
    public Result save(@RequestBody Organization organization) {
        try {
            //dict.setId(idWorker.nextId());
            boolean rs = iOrganizationService.save(organization);
            return new Result(rs ? Code.OK : Code.ERROR);
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }

    @PutMapping("")
    public Result update(@RequestBody Organization organization) {
        try {
            boolean rs = iOrganizationService.updateById(organization);
            return new Result(rs ? Code.OK : Code.ERROR);
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id) {
        try {
            Organization organization = iOrganizationService.getById(id);
            if (organization != null) {
                QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
                staffQueryWrapper.eq("school_id", id);
                long count = iStaffService.count(staffQueryWrapper);
                if (count > 0L) {
                    return new Result(40000, "", "当前有员工，不能删除！");
                }
            }
            boolean rs = iOrganizationService.removeById(id);
            return new Result(rs ? Code.OK : Code.ERROR);
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }

    @GetMapping("/getOrganiztionList")
    public Result getOrganiztionList(@RequestParam(value = "type", required = false) Integer type) {
        List<Organization> organizationList = iOrganizationService.getOrganiztionList(type);
        return new Result(Code.OK, new PageResult(organizationList, (long) organizationList.size(), 1L));
    }

    /**
     * 设置主管
     *
     * @return
     */
    @PostMapping("/setManageId")
    public Result setManageId(@RequestBody Organization organizationBody) {
        Organization organization = iOrganizationService.getById(organizationBody.getId());
        if (organization == null) {
            return new Result(Code.ERROR, "", "部门不存在");
        }
        organization.setManageId(organizationBody.getManageId());
        iOrganizationService.updateById(organization);
        return new Result(Code.OK, "", "设置成功");
    }

    /**
     * 修改状态
     *
     * @return
     */
    @PostMapping("editStatus")
    public Result editStatus(@RequestBody Organization organization) {
        try {
            Organization organization1 = iOrganizationService.getById(organization.getId());
            if (organization1 != null) {
                if (organization1.getStatus() == 1) {
                    QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
                    staffQueryWrapper.eq("school_id", organization1.getId());
                    long count = iStaffService.count(staffQueryWrapper);
                    if (count > 0L) {
                        return new Result(40000, "", "当前有员工，不能关闭！");
                    }
                    organization1.setStatus(0);
                } else {
                    organization1.setStatus(1);
                }
                boolean rs = iOrganizationService.updateById(organization1);
                return new Result(rs ? Code.OK : Code.ERROR);
            }
            return new Result(Code.ERROR, "", "修改状态失败!");
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }


    @GetMapping("/getBysSchoolTypeList")
    public Result findAll(@RequestParam(value = "name", defaultValue = "", required = false) String name,
                          @RequestParam(value = "schoolType", defaultValue = "", required = false) Integer schoolType, // 1大校区，2校区
                          @RequestParam(value = "schoolPid", defaultValue = "", required = false) String schoolPid
    ) {

        QueryWrapper<Organization> organQueryWrapper = new QueryWrapper<>();
        organQueryWrapper.eq("deleted", 0);
        organQueryWrapper.eq("status", 1);
        organQueryWrapper.eq("type", 1);
        organQueryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        organQueryWrapper.eq(StringUtils.isNotBlank(schoolPid), "pid", schoolPid);

        if (schoolType != null) {
            if (schoolType == 1) {
                organQueryWrapper.eq("pid", 0);
            }
        }

        List<Organization> organizationList = iOrganizationService.list(organQueryWrapper);

        return new Result(Code.OK, organizationList, Code.GET_OK_MSG);
    }

}
